Rap.define('/ly/init.js', ['/ly/utils/role.js', '/ly/utils/dataStore.js','/ly/utils/guide.js','/ly/utils/directive.js','/ly/utils/filters.js'], function (role, dataStore,guide) {
    if (!Array.prototype.remove) {
        Array.prototype.remove = function (val) {
            for (var i = 0; i < this.length; i++) {
                if (this[i] == val) {
                    this.splice(i, 1);
                    break;
                }
            }
        };
    }
    let axiosCache = {}
    const CancelToken = axios.CancelToken

    //前置拦截器,主要处理显示加载状态
    axios.interceptors.request.use(function (config) {
        if (config.cache) {
            let source = CancelToken.source();
            config.cancelToken = source.token;
            var params = config.params;
            var cache_key=config.url;
            if(params){
                var keys= _.sortBy(_.keys(params));
                _.each(keys,function (key){
                   cache_key+="&"+'='+key+params[key];
                });
            }
            let data = axiosCache[cache_key];
            if (data && dayjs().unix() < data.expire) {
                source.cancel({
                    cache:data.expire,
                    data: JSON.parse(data.data)
                })
            }
        }
        if (config.loading_bar) {
            App.$loadingbar.start();
        }
        if (typeof (config.loading) == 'object') {
            Vue.set(config.loading, 'loading', true);
        }
        if (config.lock) {
            if (typeof (config.lock) == 'string') {
                config.lockLoading = App.$loading({
                    lock: true,
                    text: config.lock
                });
            } else {
                config.lockLoading = App.$loading({
                    lock: true
                });
            }
        }
        if (config.form) {
            var form = new FormData();
            _.each(config.data, function (v, k) {
                form.append(v, k);
            });
            config.data = form;
        }
        return config;
    }, function (error) {
        return Promise.reject(error);
    });

    axios.interceptors.response.use(function (response) {

            var loading_bar = response.config.loading_bar;
            if (loading_bar) {
                App.$loadingbar.end();
            }
            if (typeof (response.config.loading) == 'object') {
                Vue.set(response.config.loading, 'loading', false);
            }
            var lockLoading = response.config.lockLoading;
            if (lockLoading) {
                lockLoading.close();
            }
            var data = response.data;
            if (!data.success && data.code) {
                var msg = data.msg;
                if (data.code == '100000' ||
                    data.code == '101010' ||
                    data.code == '100010'||
                    data.code =='101011') {
                    App.$message({
                        type: 'error',
                        message: msg
                    });
                    //抛出异常防止继续
                    throw data;
                } else if (data.code == '1001') {
                    App.$confirm('用户登录状态丢失,重新登录', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(function (what) {
                        location.reload();
                    }).catch(function () {
                        location.reload();
                    });
                    throw data;
                }
            }
            if (response.config.method === 'get' &&
                response.config.cache &&
                typeof(data)==='object'&&
                data.code===undefined&&
                (data.success===undefined||data.success===true)) {
                var params = response.config.params;
                var cache_key=response.config.url;
                if(params){
                    var keys= _.sortBy(_.keys(params));
                    _.each(keys,function (key){
                        cache_key+="&"+'='+key+params[key];
                    });
                }
                axiosCache[cache_key] = {
                    expire: dayjs().unix() + response.config.cache,
                    data: JSON.stringify(response.data)
                }
            }
            return response;
        },
        function (error) {
            if (axios.isCancel(error)) return Promise.resolve(error.message);
            if(!error.config)return Promise.reject(error);
            var loading_bar = error.config.loading_bar;
            if (loading_bar) {
                App.$loadingbar.end();
            }
            if (typeof (error.config.loading) == 'object') {
                Vue.set(error.config.loading, 'loading', false);
            }
            var lockLoading = error.config.lockLoading;
            if (lockLoading) {
                lockLoading.close();
                Vue.set(config.loading, 'loading', false);
            }
            console.log({
                title: '网络异常',
                message: error.message + "请检查网络",
                type: 'error'
            });

            return Promise.reject(error);
        });
    if (window.VueCodemirror) {
        Vue.use(VueCodemirror);
    }
    if (window.VueDragging) {
        Vue.use(VueDragging);
    }
    Vue.component('e-chart', VueECharts);


    Vue.component('ElDialog').mixin({
        props: {
            noTitle: Boolean,        //不显示标题
            // 添加拖动
            move: {
                type: Boolean,
                default: true,
            },
            // 内容区域可滚动
            scroll: {
                type: Boolean,
                default: true,
            },
            // 放大
            max: {
                type: Boolean,
                default: true,
            },
            top: {
                default: "0"
            }
        },
        data: function () {
            return {
                mousedownX: 0,
                mousedownY: 0,
                translateX: 0,
                translateY: 0,
                mouseupTranslateX: 0,
                mouseuptranslateY: 0,
            }
        },
        mounted: function () {
            if (this.noTitle) {
                this.$el.classList.add('el-dialog-no-title')
            }
            if (this.visible) {
                this.additional();
            }
        },
        watch: {
            visible: {
                deep: true,
                handler: function (val) {
                    if (val) {
                        this.additional();
                    } else {
                        this.destroy();
                    }
                },
            }
        },
        methods: {
            additional() {
                var me = this;
                me.$nextTick(function () {
                    me.addfullScreenBtn();
                    me.setScroll();
                    me.setMove();
                })
            },
            // 增加全屏幕按钮
            addfullScreenBtn: function () {
                if (this.max) {
                    var elDialogHeader = this.$el.getElementsByClassName('el-dialog__header')[0];
                    if (elDialogHeader) {
                        var iEl = document.createElement('i');
                        iEl.className = "el-dialog__full-screen el-icon-full-screen";
                        iEl.addEventListener('click', this.fullEvent)
                        elDialogHeader.appendChild(iEl);
                    }
                }
            },
            fullEvent() {
                var elDialog = this.$el.getElementsByClassName('el-dialog')[0];
                var elDialogBody = this.$el.getElementsByClassName('el-dialog__body')[0];
                if (elDialog.classList.contains('is-fullscreen')) {
                    // 缩小
                    elDialog.classList.remove('is-fullscreen')
                    if (this.noTitle) {
                        elDialogBody.classList.remove('no-header');
                    }
                } else {
                    // 放大
                    elDialog.classList.add('is-fullscreen')
                    // 判断有没有头部
                    if (this.noTitle) {
                        elDialogBody.classList.add('no-header');
                    }
                }
                if (this.move) {
                    var elDialog = this.$el.getElementsByClassName('el-dialog')[0];
                    elDialog.style.transform = 'translate(0px, 0px)';
                    this.mouseupTranslateX = 0;
                    this.mouseuptranslateY = 0;
                }
            },
            // 内容可滚动
            setScroll: function () {
                var me = this;
                if (this.scroll) {
                    this.$nextTick(function () {
                        var elDialogBody = me.$el.getElementsByClassName('el-dialog__body')[0];
                        if (elDialogBody) {
                            elDialogBody.classList.add('el-dialog__body-scroll');
                        }
                    })
                }
            },
            setMove: function () {
                if (this.move && this.$el) {
                    this.$el.classList.add('el-dialog__wrapper-move')
                    this.$el.addEventListener('mousedown', this.headerMousedown)
                    this.$el.addEventListener('mouseup', this.headerMouseup)
                }
            },
            // 监听可移动区域鼠标按下
            headerMousedown: function (event) {
                var elDialog = this.$el.getElementsByClassName('el-dialog')[0];
                if (event.path[0].classList.contains('el-dialog__header') && !elDialog.classList.contains('is-fullscreen')) {
                    this.mousedownX = event.screenX;
                    this.mousedownY = event.screenY;
                    this.$el.addEventListener('mousemove', this.headerMousemove);
                }
            },
            // 监听可移动区域鼠标移动
            headerMousemove: function (event2) {
                this.translateX = this.mouseupTranslateX + event2.screenX - this.mousedownX;
                this.translateY = this.mouseuptranslateY + event2.screenY - this.mousedownY;
                var elDialog = this.$el.getElementsByClassName('el-dialog')[0];
                elDialog.style.transform = 'translate(' + this.translateX + 'px, '+ this.translateY + 'px)';
            },
            // 监听可移动区域鼠标释放
            headerMouseup: function () {
                this.$el.removeEventListener('mousemove', this.headerMousemove);
                this.mouseupTranslateX = this.translateX;
                this.mouseuptranslateY = this.translateY;
            },
            destroy: function () {
                if (this.max) {
                    var iEl = this.$el.getElementsByClassName('el-dialog__full-screen')[0];
                    iEl.removeEventListener('click', this.fullEvent)
                }
                if (this.move) {
                    this.$el.removeEventListener('mousedown', this.headerMousedown)
                    this.$el.removeEventListener('mouseup', this.headerMouseup)
                }
            }
        }
    });
    Vue.component('ElDrawer').mixin({
        props: {
            noTitle: Boolean,
            // 放大
            max: {
                default: true,
            }
        },
        mounted: function () {
            this.addfullScreenBtn();
        },
        methods: {
            // 增加全屏幕按钮
            addfullScreenBtn: function () {
                if (this.max) {
                    var elDrawerHeader = this.$el.getElementsByClassName('el-drawer__header')[0];
                    if (elDrawerHeader) {
                        var iEl = document.createElement('i');
                        iEl.className = "el-drawer__full-screen el-icon-full-screen";
                        iEl.addEventListener('click', this.fullEvent)
                        elDrawerHeader.appendChild(iEl);
                    }
                }
            },
            fullEvent() {
                var elDrawer = this.$el.getElementsByClassName('el-drawer')[0];
                if (elDrawer.classList.contains('is-fullscreen')) {
                    // 缩小
                    elDrawer.classList.remove('is-fullscreen')
                } else {
                    // 放大
                    elDrawer.classList.add('is-fullscreen')
                }
            },
        },
        beforeDestroy: function () {
            if (this.max) {
                var iEl = this.$el.getElementsByClassName('el-drawer__full-screen')[0];
                iEl.removeEventListener('click', this.fullEvent)
            }
        }
    });

    var LyConfig = {
        color: {'primary': ''},
        pageInfo:{},
        simditor: {
            upload: {url: '', fileKey: ''},
            toolbar: ['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color', 'ol', 'ul', 'blockquote', 'code', 'table', 'link', 'image', 'hr', 'indent', 'outdent', 'alignment']
        },
        picUploadUrl: ''
    };
    window.Ly = {
        chart: {
            global_params: {}
        },
        guide:guide,
        role: role,
        dataStore: dataStore,
        config: function (config) {
            if (config) {
                _.extend(LyConfig, config);
            }
            return LyConfig;

        },
        errorInfo: {
            'message': '抱歉，你没有权限访问当前页面',
            'img': '/static/ly/imgs/exception/icon-403.svg',
            'code': 403
        },
        errorPage: function (config) {
            if(typeof(config)=='number'){
                config={
                    code:config
                };
            }
            var def={
                403:{img:'/static/ly/imgs/exception/icon-403.svg',message:'抱歉，你没有权限访问当前页面'},
                404:{img:'/static/ly/imgs/exception/icon-404.svg',message:'抱歉，你访问的页面不存在'},
                500:{img:'/static/ly/imgs/exception/icon-500.svg',message:'抱歉，服务器出错了'}
            };
            if(!config.img){
                config.img=def[config.code].img;
            }
            if(!config.message){
                config.message=def[config.code].message;
            }
            _.extend(this.errorInfo, config);
            App.childView = "ly-exception";
        },
        layout: {
            slide_bar: 'ly-layout-slide-all',
            url_link: '',
            center:false,
            top_bar_full: true,
            fullScreen: false,
            slide_sub: false,
            slide_bar_theme: 'light',
            top_menu_theme: 'primary',
            menu_category: '',//菜单分组
        },
        app: function (config) {
            return Rap.loadMod([
                '/ly/loadingbar/loadingbar',
                '/ly/tag',
                '/ly/icon',
                '/ly/qrcode',
                '/ly/page/navi',
                '/ly/page/page',
                '/ly/page/page-footer',
                '/ly/page/page-content',
                '/ly/code-view',
                '/ly/table/table',
                '/ly/table/table-info',
                '/ly/table/column',
                '/ly/table/column_header',
                '/ly/table/content',
                '/ly/table/header',
                '/ly/table/row',
                '/ly/table/pagination',
                '/ly/table/footer',
                '/ly/table/table-filter',
                '/ly/check/radio',
                '/ly/check/radio-group',
                '/ly/check/checkbox',
                '/ly/check/checkbox-group',
                '/ly/step/step',
                '/ly/step/steps',
                '/ly/info/number',
                '/ly/info/empty',
                '/ly/info/clamp',
                '/ly/info/skeleton',
                '/ly/info/number-info',
                '/ly/form/group',
                '/ly/form/sex',
                '/ly/form/price',
                '/ly/form/data-group',
                '/ly/form/near-picker',
                '/ly/collection/collection',
                '/ly/collection/column',
                '/ly/collection/content',
                '/ly/form/tip',
                '/ly/form/text-count',
                '/ly/layout/table',
                '/ly/info/info',
                '/ly/info/img-info',
                '/ly/page/result',
                '/ly/tip',
                '/ly/button-group',
                '/ly/panel/panel',
                '/ly/panel/content',
                '/ly/panel/header',
                '/ly/panel/panel',
                '/ly/panel/actions',
                '/ly/panel/content',
                '/ly/page_box/box',
                '/ly/page_box/left',
                '/ly/page_box/right',
                '/ly/page_box/content',
                '/ly/editor/simditor',
                '/ly/form/map_picker',
                '/ly/form/form-view',
                '/ly/form/form-line',
                '/ly/animate',
                '/ly/cropper/ly-cropper',
                '/ly/markdown',
                '/ly/source-view',
                '/ly/layout/slide_bar',
                '/ly/layout/userinfo',
                '/ly/layout/global_search',
                '/ly/layout/label_search',
                '/ly/layout/full_screen',
                '/ly/layout/header_top_nav_menu',
                '/ly/layout/slide_bar_collapse',
                '/ly/layout/slide_bar_all',
                '/ly/layout/footer',
                '/ly/exception',
                '/ly/pop-confirm',
                '/ly/upload/upload',
                '/ly/form/city_picker',
                '/ly/drawer/drawer_footer',
                '/ly/chart/chart',
                '/ly/chart/pie',
                '/ly/chart/funnel',
                '/ly/chart/top_list',
            ]).then(function () {
                var base = "/" + Rap.history_base;
                return Rap.loadScript([base + '/ly/loadingbar/index.js'])
            }).then(function () {
                Rap.onNetError(function (error) {
                    if (error instanceof XMLHttpRequest) {
                        var page = Rap.routerUrl();
                        if (page == '/layout/exception/page403' || error.status == 403) {
                            Ly.errorPage({
                                'message': '抱歉，你没有权限访问当前页面',
                                'img': '/static/ly/imgs/exception/icon-403.svg',
                                'code': 403
                            });
                        } else if (page == '/layout/exception/page500') {
                            Ly.errorPage({
                                'message': '抱歉，服务器出错了',
                                'img': '/static/ly/imgs/exception/icon-500.svg',
                                'code': 500
                            });
                        } else if (error.status >= 400 && error.status < 500) {
                            Ly.errorPage({
                                'message': '抱歉，你访问的页面不存在',
                                'img': '/static/ly/imgs/exception/icon-404.svg',
                                'code': error.status
                            });
                        } else if (error.status >= 500 && error.status < 600) {
                            Ly.errorPage({
                                'message': '抱歉，服务器出错了',
                                'img': '/static/ly/imgs/exception/icon-500.svg',
                                'code': error.status
                            });
                        }

                    } else if (error instanceof ProgressEvent) {
                        App.$notify({
                            title: '网络异常',
                            message: "Net Error " + "请检查网络",
                            type: 'error'
                        });
                    }
                });
                if (!config.mixins) {
                    config.mixins = [];
                }
                config.mixins.push({
                    data: function () {
                        return {
                            keep_include: [],
                            state: Ly.layout
                        };
                    },watch:{
                        'childView':function (){
                           var hasRole = Ly.role.checkPage();
                           if(!hasRole){
                               Ly.errorPage({
                                   'message': '抱歉，你没有权限访问当前页面',
                                   'img': '/static/ly/imgs/exception/icon-403.svg',
                                   'code': 403
                               })
                           }
                        }
                    }
                });
                if (!config.el) {
                    config.el = '#app';
                }
                window.App = Rap.app(config);
                var loading = document.getElementById('page-loading');
                loading.style.display = 'none';
                document.getElementById('app').style.display = 'block';
            })
        }
    };

    Ly.cookie = {
        set: function (name, value, days) {
            if (!days) {
                days = 30;
            }
            var exp = new Date();
            exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
            document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ';path=/';
        }, get: function (name) {
            var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg))
                return unescape(arr[2]);
            else
                return null;
        }, delete: function (name) {
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval = this.get(name);
            if (cval != null)
                document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        }
    };

    var day_js_locale = {
        name: 'zh-cn',
        weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
        weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
        weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
        months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
        monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        ordinal: (number, period) => {
            switch (period) {
                case 'W':
                    return `${number}周`
                default:
                    return `${number}日`
            }
        },
        weekStart: 1,
        yearStart: 4,
        formats: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY/MM/DD',
            LL: 'YYYY年M月D日',
            LLL: 'YYYY年M月D日Ah点mm分',
            LLLL: 'YYYY年M月D日ddddAh点mm分',
            l: 'YYYY/M/D',
            ll: 'YYYY年M月D日',
            lll: 'YYYY年M月D日 HH:mm',
            llll: 'YYYY年M月D日dddd HH:mm'
        },
        relativeTime: {
            future: '%s内',
            past: '%s前',
            s: '几秒',
            m: '1 分钟',
            mm: '%d 分钟',
            h: '1 小时',
            hh: '%d 小时',
            d: '1 天',
            dd: '%d 天',
            M: '1 个月',
            MM: '%d 个月',
            y: '1 年',
            yy: '%d 年'
        },
        meridiem: (hour, minute) => {
            const hm = (hour * 100) + minute
            if (hm < 600) {
                return '凌晨'
            } else if (hm < 900) {
                return '早上'
            } else if (hm < 1100) {
                return '上午'
            } else if (hm < 1300) {
                return '中午'
            } else if (hm < 1800) {
                return '下午'
            }
            return '晚上'
        }
    }
    dayjs.locale(day_js_locale, null, true);
    dayjs.locale('zh-cn');


    function urlJoin(base, url) {
        if (url.indexOf('/') == 0) {
            return url;
        }

        var p = base.split("/");
        if (url.indexOf('.') == -1) {
            p.pop();
            return p.join('/') + '/' + url;
        }
        // p.pop();
        p.pop();
        var pre = [];
        while (url.indexOf('../') == 0) {
            url = url.replace("../", "");
            pre.push(p.pop())
        }
        return p.join("/") + "/" + url;
    }


    Ly.pop = function (url, params, callbacks) {
        var page = Rap.global_router.page;
        url = urlJoin(page, url);
        if (!params) {
            params = {};
        }
        var div = document.createElement('div');
        document.getElementById('app').appendChild(div);
        Rap.loadMod(url).then(function () {
            url = url.split('/').join('_');
            if (!config) {
                config = {};
            }
            if (url.indexOf('_') == 0) {
                url = url.substr(1);
            }
            var c = Vue.component(url);
            var instance = new c({propsData: params})
            instance.$mount(div);
            var dialog = instance.$children[0];
            dialog.$on('open', function () {
                instance.$emit('open');
            });
            dialog.$on('close', function () {
                instance.$emit('close');
                instance.$el.parentElement.removeChild(instance.$el);
                instance.$destroy();
            });
            if (!dialog.visible) {
                dialog.$emit('update:visible', true);
            }
            if (callbacks) {
                for (var k in callbacks) {
                    instance.$on(k, callbacks[k]);
                }
            }
        });
    }

});
